package com.itheima.web.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/logoutServlet")
public class LogoutServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1. 清除session中用户信息
        request.getSession().removeAttribute("user");

        //2. 如果用户勾选 "自动登录"按钮, 退出时需要杀死Cookie
        Cookie cookie = new Cookie("autoLoginCookie", "");
        cookie.setMaxAge(0); // 立即杀死
        cookie.setPath(request.getContextPath());
        response.addCookie(cookie);

        //3. 重定向到首页
        response.sendRedirect(request.getContextPath()+"/index.jsp");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
